package cn.wh.basic.service.impl;

import cn.wh.basic.constants.BaseConstant;
import cn.wh.basic.dto.LoginDto;
import cn.wh.basic.dto.WeChatDto;
import cn.wh.basic.exception.BusinessException;
import cn.wh.basic.jwt.JwtUtils;
import cn.wh.basic.jwt.LoginResult;
import cn.wh.basic.jwt.RsaUtils;
import cn.wh.basic.service.ILoginService;
import cn.wh.basic.util.AjaxResult;
import cn.wh.basic.util.HttpClientUtils;
import cn.wh.basic.util.MD5Utils;
import cn.wh.basic.util.StrUtils;
import cn.wh.system.domain.Menu;
import cn.wh.system.mapper.MenuMapper;
import cn.wh.system.mapper.PermissionMapper;
import cn.wh.user.domain.Logininfo;
import cn.wh.user.domain.User;
import cn.wh.user.domain.Wxuser;
import cn.wh.user.mapper.LogininfoMapper;
import cn.wh.user.mapper.UserMapper;
import cn.wh.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        //校验
        if (StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(type.toString()) ) {
            throw new BusinessException("数据必填");
        }
        //通过用户名和type获取用户的信息
        Logininfo logininfo = logininfoMapper.loadByUsernameAndtype(username, type);
        //如果用户名不存在
        if (logininfo == null){
            throw new BusinessException("账户错误");
        }
        //判断密码是否正确
        //获取logininfo的盐值
        String salt = logininfo.getSalt();
        //前端输入的密码+盐值就成了和数据库里组成一样的密码了
        String byMd5 = MD5Utils.encrypByMd5(password + salt);
        //如果密码不相等
        if (!byMd5.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }

        //4.登录成功
        return loginSuccessHandler(logininfo);
        /*//通过uuid获取一个唯一的key--token
        String token = UUID.randomUUID().toString();
        //存储redis
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        //返回token + logininfo   可以用对象 map
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        //为了不让敏感信息传递,这里设为null 更安全
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
    }

    /**
     * 处理登录成功之后的逻辑
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //1.判断是否是员工吗，如果是员工，才需要查询权限
        if (logininfo.getType() == 0){
            //我们需要查询出当前登录人对应的菜单+按钮权限
            //4.1 菜单权限
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            //4.2 按钮权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            //设置给loginresult
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //把登录人信息 + 权限 加密封装成JWT串，返回给前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //使用私钥将loginResult 加密成JWT串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwtStr);// 此时的token是jwt串
        //为了不让敏感信息传递,这里设为null 更安全
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("menus",loginResult.getMenus());
        map.put("permissions",loginResult.getPermissions());
        return map;
    }

    /**
     * 微信扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        String code = dto.getCode();
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("code不能为空！！");
        }
//        1.通过code从微信获取token+openid
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL
                .replace("APPID", BaseConstant.WeChatConstants.APPID)
                .replace("SECRET", BaseConstant.WeChatConstants.SECRET)
                .replace("CODE", code);
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
//        2.通过openid查询t_wxuser表，判断是否wxuser存在并且user_id不为空
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);

//        2.1 有，且userId存在，直接免密登录===第二次之后的扫码登录
        if(wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
//            //通过uuid获取一个唯一的key--token
//            String token = UUID.randomUUID().toString();
//            //存储redis
//            redisTemplate.opsForValue().set(
//                    token,
//                    logininfo,
//                    30,
//                    TimeUnit.MINUTES
//            );
//            //返回token + logininfo   可以用对象 map
//            Map<String, Object> map = new HashMap<>();
//            map.put("token", token);
//            map.put("logininfo", logininfo);
//            //为了不让敏感信息传递,这里设为null 更安全
//            logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            map.put("logininfo",logininfo);
            return AjaxResult.my().setResultObj(loginSuccessHandler(logininfo));
        }
//        2.2 没有，这里应该让浏览器跳转到绑定页面，让它自己输入账号和密码来完成绑定
//        返回token+openid
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.my().setSuccess(false).setResultObj(binderParams);

    }
    /**
     * 微信绑定账号
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binder(WeChatDto dto) {
        Logininfo logininfo = null;
        String phone = dto.getPhone();
//            1.根据手机号 查询t_user是否已经存在
        User user = userMapper.loadByPhone(phone);
//            1.1 存在 查询出来，等着绑定
        if (user != null){
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
//            1.2 不存在 生成新的t_user + t_logininfo
        if (user == null){
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
//            2.根据token + openid 去微信查询微信的用户基本信息   ③
        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
//            3.根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
//            4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//            5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.save(wxuser);
//            6.直接免密登录
       /* String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        return loginSuccessHandler(logininfo);
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//注意：一定要手动设置type 前端用户注册  1
        return logininfo;
    }

    private User dto2User(WeChatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

}
